# coding=utf-8
#

import os
import json
import time

import concurrent.futures

from django.core.management.base import BaseCommand

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.cvm.v20170312 import cvm_client
from tencentcloud.cvm.v20170312 import models

from iminer.utils import check_pid

from iminer.tidal.models import TidalAgent


#TX_API_AK = "AKID53SmxxlMkxxlMcT9ctRp10nMirnVzJQK"
#TX_API_SK = "iFZfYEhwxlLk2oQvOlz4A7vXyDIE1c1H"
#TX_API_AK = "AKIDIarCd1C3HdwAU9zux7IjDqhCsegpGoP5"
#TX_API_SK = "waHxZdfzSh8iIHGKd8xtUzfbgOTc7rfa"
#TX_API_AK = "AKIDCbr6D86xfAUgiYDh1KUTHwPhrsiLn5B5"
#TX_API_SK = "oNjsoniUKC9yeCXfbL3e3HLBqLgx52lJ"


def delete_agents(client, server_list):
    """ """

    req = models.TerminateInstancesRequest()

    params = {"InstanceIds": server_list,
              "ReleasePrepaidDataDisks": True}

    print(params)
    req.from_json_string(json.dumps(params))

    try:
        resp = client.TerminateInstances(req)
        print(resp)
    except Exception as msg:
        print(str(msg))


def delete_agents_v2(endpoint, zone, server_list):
    """ """
    cred = credential.Credential(TX_API_AK, TX_API_SK)

    httpProfile = HttpProfile()
    httpProfile.endpoint = endpoint

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = cvm_client.CvmClient(cred, zone, clientProfile)

    req = models.TerminateInstancesRequest()

    params = {"InstanceIds": server_list,
              "ReleasePrepaidDataDisks": True}

    req.from_json_string(json.dumps(params))

    print(endpoint, zone, server_list)
    try:
        resp = client.TerminateInstances(req)
        print(resp)
    except Exception as msg:
        print(str(msg))


class Command(BaseCommand):
    help = "定时删除腾讯云的机器实例"

    def handle(self, *args, **options):
        task_name = "pid/daily_delete_tx_agent"

        try:
            old_pid = int(open(task_name).read())
        except FileNotFoundError:
            old_pid = 0
        except ValueError:
            old_pid = 0

        cur_pid = os.getpid()
        if not old_pid or not check_pid(old_pid):
            with open(task_name, "w") as fp:
                fp.write(str(cur_pid))


            limit = 100
            cred = credential.Credential(TX_API_AK, TX_API_SK)

            project_lists = [
                    {"endpoint": "cvm.ap-beijing.tencentcloudapi.com", "zone": "ap-beijing", "cn_name": "北京"},
                    #{"endpoint": "cvm.ap-nanjing.tencentcloudapi.com", "zone": "ap-nanjing", "cn_name": "南京"},
                    {"endpoint": "cvm.ap-nanjing.tencentcloudapi.com", "zone": "ap-guangzhou", "cn_name": "广州"},
                    {"endpoint": "cvm.ap-shanghai.tencentcloudapi.com", "zone": "ap-shanghai", "cn_name": "上海"},
            ]

            for project_az_info in project_lists:

                # total的数量
                offset = 0

                # 计数器
                counter = 0
                total_count = 0

                # 服务器列表，批量删除用
                server_list = []

                # 是否删完的标记
                not_done_yet = True

                # 腾讯云API初始化用的参数
                endpoint = project_az_info["endpoint"]
                zone = project_az_info["zone"]
                cn_name = project_az_info["cn_name"]

                print(endpoint, zone, cn_name)

                # 初始化腾讯云API实例
                httpProfile = HttpProfile()
                httpProfile.endpoint = endpoint

                clientProfile = ClientProfile()
                clientProfile.httpProfile = httpProfile
                client = cvm_client.CvmClient(cred, zone, clientProfile)
                req = models.DescribeInstancesRequest()

                while not_done_yet:

                    params = {"Offset": offset, "Limit": limit}
                    print(params)

                    req.from_json_string(json.dumps(params))
                    resp = client.DescribeInstances(req)

                    if not total_count:
                        total_count = resp.TotalCount
                        print(total_count, resp.TotalCount)

                    for instance_info in resp.InstanceSet:
                        instance_id = instance_info.InstanceId
                        server_list.append(instance_id)

                        #if len(server_list) >= 50:
                        #    delete_agents(client, server_list)
                        #    server_list = []

                    counter += limit
                    # 最后判断count
                    if counter >= total_count:
                        not_done_yet = False

                    offset += limit

                results = []
                per_group = 100
                with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:

                    # 提交任务到线程池，并收集Future对象  
                    splited_instance_lists = [server_list[i:i+per_group] for i in range(0, len(server_list), per_group)]
                    mt = {executor.submit(delete_agents_v2, endpoint, zone, instance_list): instance_list for instance_list in splited_instance_lists}
              
                    # 遍历Future对象，获取结果  
                    for future in concurrent.futures.as_completed(mt):
                        try:
                            data = future.result()  # 获取任务执行结果，如果任务抛出异常，这里会重新抛出  
                        except Exception as msg: 
                            print(str(msg))

